package com.ocelot.san.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.commons.lang.StringUtils;

import com.ocelot.san.dto.Lawyer;
import com.ocelot.san.form.LawyerForm;
import com.ocelot.san.service.LawyerService;


@ManagedBean(name = "lawyerController")
@ViewScoped
public class LawyerController {

	private LawyerForm lawyerForm;
	
	@ManagedProperty(value = "#{lawyerService}")
	private LawyerService lawyerService;
	
	@PostConstruct
	public void init() {
		lawyerForm = new LawyerForm();
		lawyerForm.setEditLawyer(new Lawyer());
		refreshLawyerList();
	}
	
	
	public void submitLawyer(ActionEvent event) {
		if (validateForm()) {
			lawyerService.save(lawyerForm.getEditLawyer());
			// clear Data
			lawyerForm.setEditLawyer(new Lawyer());
			refreshLawyerList();
		}
	}
	
	

	protected void refreshLawyerList() {
		lawyerForm.setLawyers(lawyerService.fetchAll());
	}
	
	public boolean validateForm() {
		List<String> errors = new ArrayList<String>();
		
		if(StringUtils.isEmpty(lawyerForm.getEditLawyer().getName())) {
			errors.add("La Descripción es requerida");
		}
		
		if(errors.size() > 0) {
			for(String error:errors){
				 FacesMessage message=new FacesMessage(error);  
				 message.setSeverity(FacesMessage.SEVERITY_INFO);  
				 FacesContext ctx= FacesContext.getCurrentInstance();  
				 ctx.addMessage("lawyerForm", message);
			}
			return false;
		}
		return true;
	}

	
	public String editItem() {
		Long idToEdit = lawyerForm.getToEdit();
		Lawyer toModify = getLawyerById(idToEdit);
		lawyerForm.setEditLawyer(toModify);
		return null;
	}

	public String removeItem() {
		Long indexToRemove = lawyerForm.getToRemove();
		Lawyer removeItem = getLawyerById(indexToRemove);
		if (removeItem != null) {
			lawyerService.delete(removeItem.getId());
			lawyerForm.getLawyers().remove(removeItem);
			lawyerForm.setEditLawyer(new Lawyer());
			refreshLawyerList();
		}
		return null;
	}
	
	protected Lawyer getLawyerById(Long id){
		return lawyerService.findById(id);
	}


	public LawyerForm getLawyerForm() {
		return lawyerForm;
	}


	public void setLawyerForm(LawyerForm lawyerForm) {
		this.lawyerForm = lawyerForm;
	}


	public LawyerService getLawyerService() {
		return lawyerService;
	}


	public void setLawyerService(LawyerService lawyerService) {
		this.lawyerService = lawyerService;
	}

	
}
